/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {
  AutoComplete,
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber,
  notification,
  Popconfirm,
  Select,
  Table
} from 'antd';

import {FormField, FormLayout, ModalFooter, SearchForm} from 'antd-extra';
import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import ViewTitle from "../../../components/ViewTitle";
import styles from "../../index.less";
import notify from "../../../components/NotificationExtra";
import MaterialElement from "../../finance/modal/MaterialElement";

const _ = require('lodash');
const {Option} = Select;
moment.locale('zh-cn');

@Form.create()
@connect(({
            user,
            global,
            material,
            sales,
            customer
          }) => ({...user, ...sales, ...material, ...global, ...customer}))
export default class ModalCreateOrEditSalesReturnOrder extends FormBase {
  constructor(props) {
    super(props);
    const {values = {}} = this.props;
    this.state = {...values};
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'customer/findMany',
      payload: {}
    });
    const payload = this.props.form.getFieldsValue();
    _.map(payload, (value, key) => {
      if (value === '') {
        payload[key] = undefined;
      }
    });
    payload.checkOutbound = true;
    this.props.dispatch({
      type: 'sales/findSalesProdMany',
      payload
    });
  }

  renderFoot = () => {
    const {foot, value, modalRef, callback, refresh, form} = this.props;

    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              const {returnCount} = values;
              const {selectedRowKeys = []} = this.state;
              if (selectedRowKeys.length === 0) {
                notify({type: 'error', message: "请选择退货物料！"});
                return;
              }
              const {salesProds = []} = this.props;
              const record = _.find(salesProds, (record) => {
                return record.pLotId === selectedRowKeys[0];
              });
              console.log('recordd', record);
              record.returnCount = returnCount;
              callback(record);
              modalRef.close();
            });
          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };


  getVendorOpt = (list) => {
    return list.map(opt => (<Option key={opt.code} value={opt.name} label={opt}>
        {opt.name}
      </Option>
    ));
  };
  onVendorSelect = (value, option) => {
    const {props} = option;
    this.state.customerBody = props.label;
    this.state.customerCode = props.label.code;
  };

  cols = () => {
    return [
      {
        title: "商品品名", dataIndex: 'prodName', key: 'prodName', render: (value, record) => {
          const {prodCode, prodName} = record;
          // return this.getProductionElement(code, value);
          return <MaterialElement code={prodCode} name={prodName}
          ></MaterialElement>;
        }
      },

      {title: "订单编码", key: "salesOrderCode", dataIndex: "salesOrderCode"},
      {title: "客户", key: "customer", dataIndex: "customer"},
      {title: "税率", key: "taxRate", dataIndex: "taxRate"},
      {title: "含税单价", key: "price", dataIndex: "price"},
      {title: "退货数量", key: "returnCount", dataIndex: "returnCount"},
      {title: "入库数量", key: "inboundCount", dataIndex: "inboundCount"},

      {
        title: "创建时间", key: "createdTs", dataIndex: "createdTs", render: (value, record) => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      }

    ];
  };
  onSelectChange = selectedRowKeys => {
    this.setState({selectedRowKeys});
  };

  render() {
    let {form, footDisabled, style, customers = [], salesProds = [], materials = [], cols = 2} = this.props;
    const {selectedRowKeys = []} = this.state;
    const rowSelection = {
      type: 'radio',
      selectedRowKeys,
      onChange: this.onSelectChange
      // getCheckboxProps: record => ({
      //   disabled: _.find(selectedDevices, item => {
      //     console.log(item.code, "disabled", record.code);
      //     return item.code === record.code;
      //   })
      // })
    };
    const onSelectRow = (record) => {
      const {pmLotId} = record;
      const temp = _.find(selectedRowKeys, item => {
        return item === pmLotId;
      });
      if (temp) {
        _.remove(selectedRowKeys, item => item === pmLotId);
      } else {
        selectedRowKeys.length = 0;
        selectedRowKeys.push(record.pLotId);
      }
      this.onSelectChange(selectedRowKeys);
    };
    return (

      <div style={{...style}}>
        <FormLayout form={form} cols={2}>
          <FormField label={'退货数量'}
                     name={'returnCount'} required={true}>
            <InputNumber></InputNumber>
          </FormField>
        </FormLayout>
        <ViewTitle title={`选择采购物料`}
                   level={1}
        ></ViewTitle>
        <SearchForm
          style={{marginLeft: '6px', marginRight: '6px'}}
          onSearch={() => {
            this.state.current = 1;
            this.componentDidMount();
          }}
          onReset={this.handleReset}
          cols={3}
          min={6}
          expandText="展开"
          form={form}
        >
          {[
            <FormField label={'订单编码'}
                       name={'salesOrderCode'}>
              <Input style={{width: '100%'}}></Input>
            </FormField>,

            <FormField
              label={'客户'}
              name={'customer'}
            >
              <AutoComplete style={{width: '100%'}}
                            dataSource={this.getVendorOpt(customers)}
                            filterOption={(inputValue, option) =>
                              option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                            }
                            allowClear
                            onSelect={this.onVendorSelect}
              >
              </AutoComplete>
            </FormField>,
            <FormField
              label={'物料'}
              name={'name'}
            >
              <AutoComplete style={{width: '100%'}}
                            dataSource={this.getVendorOpt(materials)}
                            filterOption={(inputValue, option) =>
                              option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1
                            }
                            allowClear
              >
              </AutoComplete>
            </FormField>,
            <FormField
              label={'采购日期'}
              name={'createdTs'}
              initialValue={[this.getSearchStart1Months(), this.getDefaultSearchEndDate()]}
            >
              <DatePicker.RangePicker allowClear style={{width: '100%'}}></DatePicker.RangePicker>
            </FormField>]}
        </SearchForm>
        <Table
          className={styles.antTable}
          bordered={true}
          columns={this.cols()}
          dataSource={salesProds}
          scroll={{x: true}}
          pagination={{pageSize: 100}}
          rowSelection={rowSelection}
          rowKey={record => record.pLotId}
          onRow={(record) => ({
            onClick: () => onSelectRow(record)
          })}
        ></Table>

        {!footDisabled && this.renderFoot()}
      </div>
    );
  }
}

